<?php

namespace app\store\service;

use think\facade\Db;
use WeChat\Pay;
use Exception;

class PaymentService
{

    /**
     * 生成订单号
     * @User zlchen
     * @param int $length
     * @param string $tab
     * @return string
     */
    public static function generateOrderNum($length = 6)
    {
        //20200606182556
        $dt = date('YmdHis');

        //5edb6bd-06f1a6  5edb6bd-292268   后6位不同
        $uniqid =  uniqid();

        //字符串截取 47b803
        $str_7_13 =  substr($uniqid, 7, 13);

        //str_split ( string $string [, int $split_length = 1 ] ) : array  str_split — 将字符串转换为数组
        $str_to_array = str_split($str_7_13, 1);

        //(PHP 4, PHP 5, PHP 7)  ord — 转换字符串第一个字节为 0-255 之间的值
        $arr = array_map('ord', $str_to_array); //[52,55,98,56,48,51]

        //implode — 将一个一维数组的值转化为字符串
        $arr_to_string =  implode(NULL, $arr);  //531015452102102

        //implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1)))
        //20200606182903102545
        $str = $dt . substr($arr_to_string, 0, $length);

        return $str;

    }

    public static function findPaymentConfig($store_id,$type)
    {
        $paymentConfig = Db::name('payment_config')->where(['store_id'=>$store_id,'type' => $type])->value('config');

        if (empty($paymentConfig)){
            return  [];
        }
        return  json_decode($paymentConfig,true);
    }

    public static function paymentRefund($config,$order)
    {

        $out_refund_no = PaymentService::generateOrderNum();

        switch ($order['payment_type']){
            case 1 :
                $wechat = new Pay($config);
                $result = $wechat->createRefund([
                    'transaction_id' => $order['out_trade_no'],
                    'out_refund_no' => $out_refund_no,
                    'total_fee' => (float)$order['real_amount']*100,
                    'refund_fee' => (float)$order['real_amount']*100,
                ]);

                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                    return  json(['code'=>1,'msg' => '退款成功!']);
                }

                return json(['code' => 0, 'msg' => $result['err_code_des']]);
            case 2 :
                $pay = \We::AliPayApp($config);
                try {
                    $result = $pay->refund([
                        'trade_no' => $order['out_trade_no'],
                        'out_request_no' => $out_refund_no,
                        'refund_amount' => (float)$order['real_amount'],
                    ]);
                    if ($result['code'] = 1000 && $result['msg'] == 'Success'){
                        Db::name('group_order')->where('id',$order['id'])->update(['status' => -1]);
                        Db::name('order_refund')
                            ->where('order_id',$order['id'])
                            ->update([
                                'refund_time' => time(),
                                'refund_status' => 2,
                            ]);
                        return  json(['code'=>1,'msg' => '退款成功!']);
                    }

                    return  json(['code' => 1,'msg' => $result['sub_msg']]);
                }catch (Exception $e){
                    return  ['code' => 0, 'msg' => $e->getMessage()];
                }
        }
    }


    public static function groupActivityRefund($data)
    {
        if ($data['trade_method'] == 1){
            try {
                $wechat = new Pay($data['config']);
                $result = $wechat->createRefund([
                    'out_trade_no' => $data['out_trade_no'],
                    'out_refund_no' => $data['out_refund_no'],
                    'total_fee' => (float)$data['trade_fee']*100,
                    'refund_fee' => (float)$data['trade_fee']*100,
                ]);
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                   return true;
                }
                return  false;
            }catch (\Exception $e){
                return false;
            }

        }

        if ($data['trade_method'] == 2){
            try {
                $pay = \We::AliPayApp($data['config']);
                $result = $pay->refund([
                    'out_trade_no' => $data['out_trade_no'],
                    'out_request_no' => $data['out_refund_no'],
                    'refund_amount' => (float)$data['trade_fee'],
                ]);
                if ($result['code'] = 1000 && $result['msg'] == 'Success'){
                    return true;
                }
                return  false;
            }catch (\Exception $e){
                return  true;
            }
        }
    }

    /**
     * 添加退款信息
     * */
    public static function saveRefundInfo($data)
    {
        $result = Db::name('order_refund')->insert([
                    'order_id' => $data['id'],
                    'out_trade_no' => $data['out_trade_no'],
                    'refund_fee' => $data['trade_fee'],
                    'out_refund_no' => $data['out_refund_no'],
                    'refund_status' => 1,
                    'after_sale_status' => 1,
                    'refund_reason' => '拼团失败退款'
        ]);

        return $result;
    }


    public static function paymentQuery($order_id)
    {
        $order = Db::name('order')
            ->field('id,out_trade_no,store_id,payment_type,real_amount')
            ->where('id',$order_id)
            ->find();
        $config = static::findPaymentConfig($order['store_id'],$order['payment_type']);
        $out_refund_no = PaymentService::generateOrderNum();
        switch ($order['payment_type']){
            case 1 :
                $wechat = new Pay($config);
                $result = $wechat->queryOrder([
                    'transaction_id' => $order['out_trade_no'],
                ]);

                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                    return  json(['code'=>1,'msg' => '退款成功!']);
                }

                return json(['code' => 0, 'msg' => $result['err_code_des']]);
            case 2 :
                $pay = \We::AliPayApp($config);
                try {
                    $result = $pay->query([
                        'trade_no' => $order['out_order_no'],
                        'out_request_no' => $out_refund_no,
                    ]);
                    halt($result);
                    if ($result['code'] = 1000 && $result['msg'] == 'Success'){
                        return  json(['code'=>1,'msg' => '退款成功!']);
                    }

                    return  json(['code' => 1,'msg' => $result['sub_msg']]);
                }catch (Exception $e){
                    return  ['code' => 0, 'msg' => $e->getMessage()];
                }
        }
    }

    public static function createOrder()
    {

    }

}